layui.define(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider', 'tree', 'form', 'layedit'], function (exports) {





    /**
     *  工具类构造函数
     * @constructor
     */
    var Util = {

        laydate: layui.laydate,//日期
        layer: layer,//日期
        laypage: layui.laypage,//分页
        table: layui.table,//表格
        upload: layui.upload,//上传
        element: layui.element,//元素操作
        slider: layui.slider,//滑块
        tree: layui.tree,//滑块
        form: layui.form,//表单
        layedit: layui.layedit,//富文本编辑器 

        actionMap: {
            'del': 'del',
            'add': 'add',
            'edit': 'edit'
        },

        ajax: function (url, data, success, cache, alone, async, type, dataType, error, opt) {
            var type = type || 'post';//请求类型
            var dataType = dataType;
            var async = async || true;//异步请求
            var alone = alone || false;//独立提交（一次有效的提交）
            var cache = cache || false;//浏览器历史缓存
            var ajaxStatus = true;//浏览器历史缓存

            var success = success || function (data) {
                setTimeout(function () {
                    layer.msg(data.msg);//通过layer插件来进行提示信息
                }, 500);
                if (data.status) {//服务器处理成功
                    setTimeout(function () {
                        if (data.url) {
                            location.replace(data.url);
                        } else {
                            location.reload(true);
                        }
                    }, 500);
                } else {//服务器处理失败
                    if (alone) {//改变ajax提交状态
                        ajaxStatus = true;
                    }
                }
            };
            var error = error || function (data) {

                layer.closeAll('loading');
                setTimeout(function () {
                    if (data.status == 404) {
                        layer.msg('请求失败，请求未找到');
                    } else if (data.status == 503) {
                        layer.msg('请求失败，服务器内部错误');
                    } else {
                        layer.msg('请求失败,网络连接超时');
                    }
                    ajaxStatus = true;
                }, 100);
            };
            /*判断是否可以发送请求*/
            if (!ajaxStatus) {
                return false;
            }
            ajaxStatus = false;//禁用ajax请求
            /*正常情况下1秒后可以再次多个异步请求，为true时只可以有一次有效请求（例如添加数据）*/
            if (!alone) {
                setTimeout(function () {
                    ajaxStatus = true;
                }, 100);
            }

            var _opt = $.extend({
                'url': url,
                'data': data,
                'type': type,
                'cache': cache,
                'dataType': dataType,
                'async': async,
                'success': success,
                'error': error,
                'jsonpCallback': 'jsonp' + (new Date()).valueOf().toString().substr(-4),
                'beforeSend': function () {
                    layer.msg('加载中', {
                        icon: 16,
                        shade: 0.01
                    });
                }
            }, opt);
            $.ajax(_opt);
        },

        // submitAjax(post方式提交)
        submitAjax: function (form, success, cache, alone) {
            cache = cache || true;
            var form = $(form);
            var url = form.attr('action');
            var data = form.serialize();
            this.ajax(url, data, success, cache, alone, false, 'post', 'json');
        },
        // ajax提交(post方式提交)
        post: function (url, data, success, cache, alone) {
            this.ajax(url, data, success, cache, alone, false, 'post', 'json');
        },

        // ajax提交(get方式提交)
        get: function (url, success, cache, alone) {
            this.ajax(url, {}, success, cache, alone, false, 'get', 'json');
        },

        // jsonp跨域请求(get方式提交)
        jsonp: function (url, success, cache, alone) {
            this.ajax(url, {}, success, cache, alone, false, 'get', 'jsonp');
        },
        send: function (url, data, opt) {
            this.ajax(url, data, opt.success, opt.cache, opt.alone, opt.async, opt.type, opt.contentType, opt.error, opt);
        },


        getTime: function (time, fmt) {
            return date(fmt || 'Y-m-d H:i:s', new String(time));
        },

        // templateProxy
        templateProxy: function (htmlUrl, data, opt) {

            var self = this;

            var html = this.getTemPlates(htmlUrl);

            var _opt = $.extend({
                    type: 1
                    , offset: 'auto'
                    , id: 'editAttrs'
                    , content: $.templates(html).render(data)
                    , area: ['500px', '300px']
                    , btn: ['确定', '关闭']
                    , btnAlign: 'c' //按钮居中
                    , shade: 0 //不显示遮罩
                    , yes: function (index, e) {
                        if (opt.confirm && $.isFunction(opt.confirm)) {
                            opt.confirm.call(this, self.getFormData($(e).find('form')), e, layer)
                        }
                    }
                    ,
                    btn2: function (index, e) {
                        if (opt.cancel && $.isFunction(opt.cancel)) {
                            opt.cancel.call(this, index, e, layer);
                        }
                    }
                }, opt
            );
            layer.open(_opt);
        },
        /**
         * getFormData
         * @param form
         */
        getFormData: function (form) {
            var values = {};
            var _form = $(form);

            if (!_form.length) {
                return values;
            }

            var data = _form.serializeArray();

            for (var item in data) {
                values[data[item].name] = data[item].value;
            }

            return values;
        },
        /**
         * 获取前端html模板方法<!注意 模板命名已模块名开头,请求路径为resources/moduleName/*.html>
         *
         * @param {[type]}
         *            [url] [模板资源名称]
         * @return {[type]} [description]
         */
        getTemPlates: function (url) {
            var self = this;
            var templateHtmlTpl = null;
            self.send(url, null, {
                type: "get", //静态资源使用get方式请求
                dataType: "html",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                async: false,
                success: function (resp) {
                    templateHtmlTpl = resp;
                }
            });
            return templateHtmlTpl;
        },

        selected: function () {
            var model = location.href;
            var $model = $('.models[href="' + model.slice(model.lastIndexOf(appUrl)) + '"]');
            $model.closest('dd').addClass('layui-this').siblings('.dd').removeClass("layui-this");
            var nav = $model.closest(".layui-nav-item");
            nav.addClass("layui-nav-itemed").siblings('.layui-nav-item').removeClass("layui-nav-itemed");
        }
    };

    exports('customUtil', Util);
});